// pages/search/search.js
const storeService = require('../../../../api/storeService.js')
const productService = require('../../../../api/productService.js')
const shopcartService = require('../../../../api/shopcartService.js')
const util = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

const recorderManager = wx.getRecorderManager()

function sendRecord(src, storeId) {
  wx.showToast({
    icon: 'loading',
    title: '正在搜索...',
    duration: 20000
  })
  var obj = {
    //服务器地址
    url: "https://dev.gomoretech.com/demo/newretail-search/api/search/product/queryByVoice",
    filePath: src,
    name: "file",
    header: {
      'Content-Type': 'application/json'
    },
    formData: {
      'storeId': storeId
    },
    success: function (result) {
      // console.log(result)
      var data = JSON.parse(result.data);
      var page = getCurrentPages();
      var indexPage = null
      page.forEach(item => {
        if (item.route === "pages/search/search") {
          indexPage = item
        }
      })
      wx.hideToast()
      if (data.data) {
        indexPage.setProduct(data.data)
      } else {
        wx.showToast({
          title: '未检测到语音',
          icon: 'none',
          duration: 2000
        })
      }
      // setSearchData(data)
    },
    fail: function (err) {
      console.log(err);
      wx.hideToast()
    }
  };
  wx.uploadFile(obj)
}

recorderManager.onStart(() => {
  console.log('recorder start')
})
recorderManager.onPause(() => {
  console.log('recorder pause')
})
recorderManager.onStop((res) => {
  console.log('recorder stop', res)
  const {
    tempFilePath
  } = res
})
recorderManager.onFrameRecorded((res) => {
  const {
    frameBuffer
  } = res
  console.log('frameBuffer.byteLength', frameBuffer.byteLength)
})

recorderManager.onError((res) => {
  console.log("error", res);
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    storeId: '',
    store: '',
    page: 1,
    pageSize: 0,
    searchCount: true,
    searchLabelShow: false,
    searchFocus: true,
    searchText: '请输入搜索内容',
    searchItem: "",
    goodsList: [],
    searchHistory: [],
    nameLikes: '',
    placeholderText: '',
    keyboardHeight: 0,
    recorderType: 'normal', //normal (正常) success (成功) fail (失败) cancel (取消)
    toast: {
      show: false,
      title: '向上滑动取消',
      image: '../../../../image/iconMicrophoneWhite.png'
    },
    phone: false
  },

  // 搜索框点击事件,输入框聚焦
  handleFocus: function (e) {
    this.setData({
      searchLabelShow: true,
      goodsList: [],
      searchItem: ''
    })
  },
  // 搜索框聚焦事件
  handleInputFocus: function (e) {
    console.log(e.detail)
    this.setData({
      keyboardHeight: e.detail.height
    })
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false,
        goodsList: [],
        keyboardHeight: 0,
        placeholderText: '',
      })
    } else {
      this.setData({
        keyboardHeight: 0
      })
    }
  },
  // 输入框输入时处理
  handleInput: function (e) {
    this.setData({
      nameLikes: e.detail.value,
      placeholderText: ''
    })
  },
  toSearch: function () {
    const that = this
    let nameLikes = this.data.nameLikes
    if (!nameLikes) {
      wx.showToast({
        title: '请输入您想搜索的商品名称！',
        icon: "none",
        duration: 2000
      })
    } else {
      nameLikes = nameLikes.replace(/(^\s*)|(\s*$)/g, "");
      that.setData({
        searchItem: nameLikes,
        searchLabelShow: true
      })
      this.getSearchProduct(nameLikes)
    }
  },
  // 搜索框确定处理
  handleConfirm: function (e) {
    console.log(e)
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false,
        keyboardHeight: 0
      })
      wx.showToast({
        title: '请输入您想搜索的商品名称！',
        icon: "none",
        duration: 2000
      })
    } else {
      var nameLikes = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
      this.getSearchProduct(nameLikes)
    }
  },
  getSearchProduct: function (nameLikes) {
    var storeId = this.data.storeId;
    const that = this
    var page = this.data.page;
    var pageSize = this.data.pageSize;
    var searchCount = this.data.searchCount;
    console.log(nameLikes)
    productService.getSearchProduct(storeId, page, pageSize, nameLikes, searchCount).then(res => {
      console.log(res);
      let tempList = []
      if (res.records && res.records.length > 0) {
        res.records.forEach(item => {
          let produtlabel = []
          let promotions = []
          let specifications = ''
          if (item.labels && item.labels.length > 0) {
            item.labels.forEach(ele => {
              if (ele.type === 'GOODSLABEL') {
                produtlabel.push(ele)
              } else if (ele.type === 'PROMOTIONLABEL') {
                promotions.push(ele)
              }
            })
          }
          if (item.productProperties && item.productProperties.length > 0) {
            for (let i = 0; i < item.productProperties.length; i++) {
              const ele = item.productProperties[i];
              if (ele.propertyName === '规格') {
                specifications = ele.propertyValue
                break
              }
            }
          }
          let tempItem = {
            ...item,
            produtlabel: produtlabel,
            promotions: promotions,
            specifications: specifications
          }
          tempList.push(tempItem)
        })
        that.setData({
          goodsList: tempList,
          searchLabelShow: true
        })
      } else {
        wx.showToast({
          title: '没有您想搜索的商品！',
          icon: "none",
          duration: 2000
        })
      }
    })
    this.setSearchHistory(nameLikes)
  },
  // 设置搜索历史缓存及数组
  setSearchHistory: function (nameLikes) {
    var searchData = this.data.searchHistory;
    searchData.unshift(nameLikes);
    var newSetData = new Set(searchData);
    var newSearchData = Array.from(newSetData);
    wx.setStorageSync('searchDataLog', newSearchData);
    var SearchDataCache = newSearchData.slice(0, 10)
    this.setData({
      searchHistory: SearchDataCache
    })
  },
  toGoodsDetail: function (val) {
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?productId=' + val.currentTarget.id + '&storeId=' + this.data.storeId + '&type=normal'
    })
  },
  // 点击搜索记录
  clickSearchItem: function (e) {
    const that = this;
    that.handleFocus();
    that.setData({
      searchItem: e.currentTarget.dataset.value,
      nameLikes: e.currentTarget.dataset.value
    })
    var nameLikes = that.data.searchItem
    that.getSearchProduct(nameLikes)
  },
  // 清除历史记录
  clearSearchHistory: function () {
    const that = this;
    wx.removeStorageSync('searchDataLog')
    that.setData({
      searchHistory: []
    })
  },
  // toast相关
  showGMToast: function ({
    title: title,
    image: image
  }) {
    const that = this
    that.setData({
      toast: {
        show: true,
        title: title,
        image: image
      }
    })
  },
  hideGMToast: function () {
    this.setData({
      toast: {
        ...this.data.toast,
        show: false,
      }
    })
  },
  setProduct: function (data) {
    console.log(data);
    const that = this
    let tempList = []
    if (data.voiceName) {
      that.setData({
        searchItem: data.voiceName,
        nameLikes: data.voiceName,
        placeholderText: data.voiceName,
        searchLabelShow: true,
        searchFocus: false
      })
    }
    if (data.results.records && data.results.records.length > 0) {
      data.results.records.forEach(item => {
        let produtlabel = []
        let promotions = []
        let specifications = ''
        if (item.labels && item.labels.length > 0) {
          item.labels.forEach(ele => {
            if (ele.type === 'GOODSLABEL') {
              let tempData = {
                id: ele.product_id,
                color: ele.label_color,
                imageUrl: ele.image_url,
                labelDetails: ele.label_details,
                labelName: ele.label_name,
                pictureHeight: ele.picture_height,
                pictureWidth: ele.picture_width,
                type: ele.type
              }
              produtlabel.push(tempData)
            } else if (ele.type === 'PROMOTIONLABEL') {
              let tempData = {
                id: ele.product_id,
                color: ele.label_color,
                imageUrl: ele.image_url,
                labelDetails: ele.label_details,
                labelName: ele.label_name,
                pictureHeight: ele.picture_height,
                pictureWidth: ele.picture_width,
                type: ele.type
              }
              promotions.push(tempData)
            }
          })
        }
        if (item.productProperties && item.productProperties.length > 0) {
          for (let i = 0; i < item.productProperties.length; i++) {
            const ele = item.productProperties[i];
            if (ele.propertyName === '规格') {
              specifications = ele.propertyValue
              break
            }
          }
        }
        let tempItem = {
          ...item,
          id: item.product_id,
          soldCount: item.sold_count,
          sellPrice: item.sell_price,
          name: item.product_name,
          description: '',
          imageUrl: item.url,
          originalPrice: item.original_price,
          produtlabel: produtlabel,
          promotions: promotions,
          specifications: specifications
        }
        tempList.push(tempItem)
      })
      console.log(tempList)
      that.setData({
        goodsList: tempList,
        searchLabelShow: true
      })
      try {
        var value = wx.getStorageSync('wj_speechSearch')
        if (value) {
          wx.removeStorageSync('wj_speechSearch')
        }
      } catch (e) {
        // Do something when catch error
      }
    } else {
      // wx.showToast({
      //   title: '没有您想搜索的商品！',
      //   icon: "none",
      //   duration: 2000
      // })
      this.getStoreProduct(this.data.storeId)
    }
  },

  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  // 获取门店精选商品
  getStoreProduct: function (storeId) {
    const that = this
    let page = 1
    let pageSize = 0
    let business = 'RETAIL'
    let hot = true
    let postData = {
      page: page,
      pageSize: pageSize,
      hot: hot,
      storeIdEquals: storeId,
      business: business
    }
    productService.query(postData).then(res => {
      console.log(res)
      let tempList = []
      if (res.records && res.records.length > 0) {
        res.records.forEach(item => {
          let produtlabel = []
          let promotions = []
          let specifications = ''
          if (item.labels && item.labels.length > 0) {
            item.labels.forEach(ele => {
              if (ele.type === 'GOODSLABEL') {
                produtlabel.push(ele)
              } else if (ele.type === 'PROMOTIONLABEL') {
                promotions.push(ele)
              }
            })
          }
          if (item.productProperties && item.productProperties.length > 0) {
            for (let i = 0; i < item.productProperties.length; i++) {
              const ele = item.productProperties[i];
              if (ele.propertyName === '规格') {
                specifications = ele.propertyValue
                break
              }
            }
          }
          let tempItem = {
            ...item,
            produtlabel: produtlabel,
            promotions: promotions,
            specifications: specifications
          }
          tempList.push(tempItem)
        })
        let newTempList = that.productsSort(tempList)
        that.setData({
          goodsList: newTempList,
          searchFocus: false
        })
      } else {
        that.setData({
          goodsList: tempList
        })
      }
    })
  },
  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  // 语音相关
  /**
   * 录音开始
   */
  recorderStart: function (e) {
    const that = this
    let touchDotX = e.touches[0].pageX; // 获取触摸时的原点
    let touchDotY = e.touches[0].pageY;
    let time = 0
    // 使用js计时器记录时间    
    let interval = setInterval(function () {
      time++;
    }, 100);
    this.setData({
      touchDotX: touchDotX,
      touchDotY: touchDotY,
      interval: interval,
      time: time
    })
    that.showGMToast({
      title: '向上滑动取消',
      image: '../../../../image/iconMicrophoneWhite.png',
    })
    const options = {
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'aac',
      frameSize: 50
    }
    recorderManager.start(options)
    recorderManager.onStart(() => {
      console.log("录音开始")
      that.setData({
        recorderType: 'success'
      })
    })
  },
  /**
   * 录音取消
   */
  recorderCancel: function (e) {
    console.log('录音取消', e)
    this.hideGMToast()
    recorderManager.stop()
    that.setData({
      recorderType: 'cancel'
    })
  },
  /**
   * 触摸移动（上滑取消）
   */
  recorderMove: function (e) {
    const that = this
    let touchDotX = this.data.touchDotX
    let touchDotY = this.data.touchDotY
    let interval = this.data.interval
    let time = this.data.time
    let touchMoveX = e.changedTouches[0].pageX;
    let touchMoveY = e.changedTouches[0].pageY;
    let tmX = touchMoveX - touchDotX;
    let tmY = touchMoveY - touchDotY;
    if (time < 20) {
      let absX = Math.abs(tmX);
      let absY = Math.abs(tmY);
      if (absX > 2 * absY) {
        if (tmX < 0) {
          console.log("左滑=====")
        } else {
          console.log("右滑=====")
        }
      }
      if (absY > absX * 2) {
        if (tmY < 0) {
          that.showGMToast({
            title: '取消发送',
            image: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconMicrophoneBack.png',
          })
          recorderManager.pause()
          that.setData({
            recorderType: 'cancel'
          })
        } else {
          recorderManager.resume()
          that.showGMToast({
            title: '向上滑动取消',
            image: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconMicrophoneWhite.png',
          })
          that.setData({
            recorderType: 'success'
          })
        }
      }
    }
    clearInterval(interval); // 清除setInterval
    this.setData({
      time: 0
    })
  },
  /**
   * 录音结束
   */
  recorderEnd: function (e) {
    console.log("录音结束")
    const that = this
    let recorderType = this.data.recorderType
    that.hideGMToast()
    //结束录音  
    recorderManager.stop()
    if (recorderType === 'success') {
      console.log("success", recorderType)
      recorderManager.onStop((res) => {
        const tempFilePath = res.tempFilePath
        console.log(tempFilePath)
        sendRecord(tempFilePath, that.data.storeId)
      })
    } else {

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this;
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        store: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id
      })
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy

          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
            } else {
              // 查询所有门店
              storeService.queryList().then(res => {
                var allStores = res;
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.getMenuProduct(res.id)
              })
            }
          } catch (e) {
            // Do something when catch error
          }
        }
      })
    }
    if (options.keyword && options.type === 'atOnce') {
      // self.handleFocus()
      if ("" != wx.getStorageSync('searchDataLog')) {
        self.setData({
          searchHistory: wx.getStorageSync('searchDataLog').slice(0, 10),
          searchItem: options.keyword,
          nameLikes: options.keyword,
          placeholderText: options.keyword,
          searchLabelShow: true,
          searchFocus: false
        });
      } else {

      }
      self.getSearchProduct(options.keyword)
    } else if (options.keyword && options.type === 'wait') {
      self.handleFocus()
      if ("" != wx.getStorageSync('searchDataLog')) {
        self.setData({
          searchHistory: wx.getStorageSync('searchDataLog').slice(0, 10),
        });
      } else {

      }
      self.setData({
        // searchItem: options.keyword,
        nameLikes: options.keyword,
        placeholderText: options.keyword,
      })
    } else {
      self.handleFocus()
      if ("" != wx.getStorageSync('searchDataLog')) {
        self.setData({
          searchHistory: wx.getStorageSync('searchDataLog').slice(0, 10)
        });
      } else {

      }
    }
    try {
      var value = wx.getStorageSync('wj_speechSearch')
      if (value) {
        console.log(value)
        self.setProduct(value)
        self.setData({
          searchFocus: false
        })
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/goods/search/search?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {}
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/goods/search/search',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {}
      }
    }
  },

  /**
   * 检查当前用户是否登录授权
   */
  checkAuth: function () {
    try {
      if (!app.globalData.userInfo) {
        return false;
      } else {
        return true;
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  addShopcartTest: function (val) {

  },

  /**
   * 添加购物车
   */
  bindsubmit: function (val) {
    console.log(val.detail)
    const that = this
    var productId = val.detail.target.dataset.id;
    let business = val.detail.target.dataset.business;
    let balance = val.detail.target.dataset.balance;
    let storeId = ''
    let loginStatus = this.checkAuth()
    console.log(loginStatus)
    if (loginStatus) {
      if (business === "DISTRIBUTION") {
        try {
          var data = wx.getStorageSync('wj_distributionStore')
          if (data) {
            storeId = data.id
          }
        } catch (e) {}
      } else {
        storeId = app.globalData.storeInfo.id
      }
      var postData = {
        storeId: storeId,
        lists: [{
          count: 1,
          productId: productId
        }]
      }
      if (business === 'DISTRIBUTION') {
        balance = 0
        console.log(storeId, productId)
        productService.getDetails(storeId, productId).then(res => {
          console.log(res)
          balance = res.balance
          addShopcart(balance)
        })
      } else {
        addShopcart(balance)
      }

      function addShopcart(balance) {
        if (app.globalData.userInfo.member) {
          if (balance === 0 || balance === null || balance === '') {
            wx.showToast({
              title: '门店中该商品库存不足，请选购其他商品~',
              icon: 'none',
              duration: 2000
            })
          } else {
            try {
              wx.setStorageSync('wj_wxa_formId', val.detail.formId)
            } catch (e) {}
            shopcartService.cateringAdd(postData).then(res => {
              console.log(res)
              wx.showToast({
                title: '添加购物袋成功~',
                icon: 'none',
                duration: 2000
              })
            }).catch(err => {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } else {
          that.handlePopupPhone()
          // wx.showToast({
          //   title: '请先绑定手机号码后再添加哦~',
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    } else {
      wx.showToast({
        title: '请先点击头像授权登录后添加哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    try {
      if (!app.globalData.userInfo) {
        return false;
      } else {
        return true;
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})